﻿#region Vương văn hùng
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Common;
using System.Data.Sql;
using System.Data.SqlClient;
using Service;
using SetupConfig;

namespace Hosting_Management
{
    public partial class frmQuanLy : Form
    {
        #region New Object
        private Service.Processing con = null;
        private string ServerName = string.Empty;
        private string DatabaseName = string.Empty;
        public frmQuanLy()
        {
            InitializeComponent();
            btnStop.Enabled = false;
            btnStart.Enabled = true;
            lblMessage.Text = "Turn Off !";
            lblMessage.ForeColor = Color.Red;
        }
        #endregion

        #region Connects SQL
        private void SelectServerName()
        {
            try
            {
                string sqlName = string.Empty;
                this.cbxServer.Items.Clear();
                SqlServerList SqlSL = new SqlServerList();
                SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
                DataTable table = instance.GetDataSources();
                foreach (DataRow row in table.Rows)
                {
                    SqlSL = new SqlServerList();
                    SqlSL.ServerName = row[0].ToString();
                    SqlSL.InstanceName = row[1].ToString();
                    if (string.IsNullOrEmpty(SqlSL.InstanceName))
                        sqlName = SqlSL.ServerName;
                    else
                        sqlName = SqlSL.ServerName + "\\" + SqlSL.InstanceName;
                    this.cbxServer.Items.Add(sqlName);
                }
            }
            catch
            { }
        }

        private void SelectDatabase()
        {
            SqlDataReader read;
            SqlConnection conect = new SqlConnection();
            try
            {
                cbxDatabase.Items.Clear();
                conect.ConnectionString = "Data Source=" + cbxServer.Text.ToString() + ";" + "Initial Catalog=master;Integrated Security = SSPI;";
                conect.Open();
                SqlCommand cmd = new SqlCommand("SELECT name FROM sys.databases", conect);
                cmd.CommandType = CommandType.Text;
                read = cmd.ExecuteReader();
                while (read.Read())
                {
                    cbxDatabase.Items.Add(read["name"].ToString());
                }
                read.Close();
                conect.Close();
            }
            catch
            { }
        }
        #endregion
        private static string connectName = string.Empty;
        #region Load
        private void frmQuanLy_Load(object sender, EventArgs e)
        {
            try
            {
                SelectServerName();
                try
                {
                    System.Reflection.Assembly getfile = System.Reflection.Assembly.GetExecutingAssembly();
                    SetupConfig.Variable vl = new SetupConfig.Variable();
                    vl.HanhDong = "1";
                    vl.FileName = getfile.Location + ".config";
                    SetupConfig.Variable[] list = SetupConfig.Config.GetConfig(vl);
                    if (list != null)
                    {
                        for (int i = 0; i < list.Length; i++)
                        {
                            switch (list[i].KeyName)
                            {
                                case "Namespace":
                                    txtName.Text = list[i].KeyValue;
                                    break;
                                case "AddressIP":
                                    txtIP.Text = list[i].KeyValue;
                                    break;
                                case "Port":
                                    txtPort.Text = list[i].KeyValue;
                                    break;
                                case "Http":
                                    txtHTTP.Text = list[i].KeyValue;
                                    break;
                                case "DataSource":
                                    cbxServer.Text = list[i].KeyValue;
                                    connectName += "Data Source=" + list[i].KeyValue;
                                    break;
                                case "InitialCatalog":
                                    cbxDatabase.Text = list[i].KeyValue;
                                    connectName += ";Initial Catalog=" + list[i].KeyValue;
                                    break;
                                case "UserID":
                                    txtUserName.Text = list[i].KeyValue;
                                    connectName += ";User ID=" + list[i].KeyValue;
                                    break;
                                case "Password":
                                    txtPassword.Text = list[i].KeyValue;
                                    connectName += ";Password=" + list[i].KeyValue+";";
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Lỗi hãy liên hệ với nhà quản trị","Thông báo");
                    return;
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }
        #endregion

        #region Event
        private void cbxServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ServerName = cbxServer.Text;
            SelectDatabase();
        }

        private void cbxDatabase_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.DatabaseName = cbxDatabase.Text;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                con = new Processing();
                if (txtName.Text == string.Empty)
                {
                    MessageBox.Show("Nhập namespase !", "Thông báo");
                    txtName.Focus();
                    return;
                }
                con.Names = txtName.Text;
                if (txtIP.Text == string.Empty)
                {
                    MessageBox.Show("Nhập address ip !", "Thông báo");
                    txtIP.Focus();
                    return;
                }
                con.IP = txtIP.Text;
                int p;
                try
                {

                    if (txtPort.Text == string.Empty)
                    {
                        MessageBox.Show("Nhập port !", "Thông báo");
                        txtPort.Focus();
                        return;
                    }
                    p = int.Parse(txtPort.Text);
                }
                catch (Exception)
                {
                    p = 2011;
                }
                con.Port = p;
                if (SaveConfig(txtName.Text.Trim(), txtIP.Text.Trim(), txtPort.Text.Trim(), txtHTTP.Text.Trim()) == true)
                {
                    con.Link = txtHTTP.Text;
                    Boolean ch = con.Start();
                    if (ch == true)
                    {
                        btnStart.Enabled = false;
                        btnStop.Enabled = true;
                        lblMessage.Text = "Turn On !";
                        lblMessage.ForeColor = Color.Green;
                    }
                    else
                    {
                        MessageBox.Show("Thất bại ! Hãy liên hệ với nhà quản trị", "Thông báo");
                        btnStart.Enabled = true;
                        btnStop.Enabled = false;
                        lblMessage.Text = "Turn Off !";
                        lblMessage.ForeColor = Color.Red;
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("Lỗi file App.config ! Hãy liên hệ với nhà quản trị","Thông báo");
                    return;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Thất bại ! Hãy liên hệ với nhà quản trị", "Thông báo");
                btnStart.Enabled = true;
                btnStop.Enabled = false;
                lblMessage.Text = "Turn Off !";
                lblMessage.ForeColor = Color.Red;
                return;
            }
        }

        private Boolean SaveConfig(string name,string ip,string port,string url)
        {
            Boolean kt = false;
            try
            {
                System.Reflection.Assembly getfile = System.Reflection.Assembly.GetExecutingAssembly();
             
                SetupConfig.Variable names = new SetupConfig.Variable();
                names.FileName = getfile.Location + ".config";
                names.KeyName = "Namespace";
                names.KeyValue = name;
                kt = SetupConfig.Config.SaveConfigData(names);
                if (kt == false)
                { return kt; }
                SetupConfig.Variable address = new SetupConfig.Variable();
                address.FileName = getfile.Location + ".config";
                address.KeyName = "AddressIP";
                address.KeyValue = ip;
                kt = SetupConfig.Config.SaveConfigData(address);
                if (kt == false)
                { return kt; }
                SetupConfig.Variable ports = new SetupConfig.Variable();
                ports.FileName = getfile.Location + ".config";
                ports.KeyName = "Port";
                ports.KeyValue = port;
                kt = SetupConfig.Config.SaveConfigData(ports);
                if (kt == false)
                { return kt; }
                SetupConfig.Variable link = new SetupConfig.Variable();
                link.FileName = getfile.Location + ".config";
                link.KeyName = "Http";
                link.KeyValue = url;
                kt= SetupConfig.Config.SaveConfigData(link);
                if (kt == false)
                { return kt; }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                kt = false;
            }
            return kt;
        }
        private Boolean SaveConnectionSQL(string server, string database, string userName, string password)
        {
            Boolean kt = false;
            try
            {
                System.Reflection.Assembly getfile = System.Reflection.Assembly.GetExecutingAssembly();

                SetupConfig.Variable DataSource = new SetupConfig.Variable();
                DataSource.FileName = getfile.Location + ".config";
                DataSource.KeyName = "DataSource";
                DataSource.KeyValue = server;
                kt = SetupConfig.Config.SaveConfigData(DataSource);
                if (kt == false)
                { return kt; }
                SetupConfig.Variable InitialCatalog = new SetupConfig.Variable();
                InitialCatalog.FileName = getfile.Location + ".config";
                InitialCatalog.KeyName = "InitialCatalog";
                InitialCatalog.KeyValue = database;
                kt = SetupConfig.Config.SaveConfigData(InitialCatalog);
                if (kt == false)
                { return kt; }
                SetupConfig.Variable UserID = new SetupConfig.Variable();
                UserID.FileName = getfile.Location + ".config";
                UserID.KeyName = "UserID";
                UserID.KeyValue = userName;
                kt = SetupConfig.Config.SaveConfigData(UserID);
                if (kt == false)
                { return kt; }
                SetupConfig.Variable Password = new SetupConfig.Variable();
                Password.FileName = getfile.Location + ".config";
                Password.KeyName = "Password";
                Password.KeyValue = password;
                kt = SetupConfig.Config.SaveConfigData(Password);
                if (kt == false)
                { return kt; }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                kt = false;
            }
            return kt;
        }
        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnStart.Enabled == true)
                {
                    MessageBox.Show("Bạn phải bật service mới có thể tắt", "Thông báo");
                    return;
                }
                con.Stop();
                btnStart.Enabled = true;
                btnStop.Enabled = false;
                lblMessage.Text = "Turn Off !";
                lblMessage.ForeColor = Color.Red;
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                MessageBox.Show("Lỗi: " + s, "Thông báo");
                return;
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnStop.Enabled == true)
                {
                    MessageBox.Show("Bạn phải tắt service mới có thể đóng form này", "Thông báo");
                    return;
                }
                Application.Exit();
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                MessageBox.Show("Lỗi: " + s, "Thông báo");
                return;
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (cbxServer.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Nhập tên server !", "Thông báo");
                    return;
                }
                if (cbxDatabase.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Nhập tên database !", "Thông báo");
                    return;
                }
                if (txtUserName.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Nhập tên đăng nhập !", "Thông báo");
                    return;
                }
                if (txtPassword.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Nhập mật khẩu đăng nhập !", "Thông báo");
                    return;
                }
                if (SaveConnectionSQL(cbxServer.Text.Trim(), cbxDatabase.Text.Trim(), txtUserName.Text.Trim(), txtPassword.Text.Trim()) == true)
                {
                    connectName = "Data Source=" + cbxServer.Text.Trim() + ";Initial Catalog=" + cbxDatabase.Text.Trim() + ";User ID=" + txtUserName.Text.Trim() + ";Password=" + txtPassword.Text.Trim() + ";";
                    MessageBox.Show("Đã lưu lại","Thông báo");
                    Common.StaticVariable.ConnectionString = connectName;
                    return;
                }
                else
                { 
                    MessageBox.Show("Lỗi file App.config ! Hãy liên hệ với nhà quản trị", "Thông báo"); 
                    return;
                }
              
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }

        private void txtPort_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                Common.ValidateControl.CheckString(e);
            }
            catch (Exception)
            {}
        }

        private void txtName_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                 Common.ValidateControl.CheckNumber(e);
            }
            catch (Exception)
            { }
        }

        private void txtName_TextChanged(object sender, EventArgs e)
        {
            try
            {
                txtHTTP.Text = "http://127.0.0.1:2012/"+txtName.Text.Trim()+"/";
            }
            catch (Exception)
            { }
        }

        private void txtIP_TextChanged(object sender, EventArgs e)
        {
            try
            {
                txtHTTP.Text = "http://" + txtIP.Text.Trim() +":2012/" + txtName.Text.Trim() + "/";
            }
            catch (Exception)
            { }
        }

        private void txtPort_TextChanged(object sender, EventArgs e)
        {
            try
            {
                txtHTTP.Text = "http://" + txtIP.Text.Trim() + ":"+txtPort.Text.Trim()+"/" + txtName.Text.Trim() + "/";
            }
            catch (Exception)
            { }
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection con =new SqlConnection("Data Source="+cbxServer.Text+";Initial Catalog="+cbxDatabase.Text+";User ID="+txtUserName.Text+";Password="+txtPassword.Text);
                con.Open();
                MessageBox.Show("Kết nối thành công");
                con.Close();
            }
            catch (Exception)
            {

                MessageBox.Show("Kết nối thất bại, hãy xem lại thông số!","Thông báo");
            }
        }
    }
}
#endregion
